<?php

namespace App\Http\Controllers\Api\System;

use App\Library\api_sdk\SmsDemo;
use App\System\ErrorModel;
use App\User\UserBaseModel;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Cache;
use App\Library\sms\top\request\AlibabaAliqinFcSmsNumSendRequest;
use App\Library\sms\top\TopClient;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

class CoreController extends Controller
{
    public function reg_mail()
    {
        //
    }

    /**
     * @param string        $token      存储的token key
     * @param UserBaseModel $user_info  存储的用户信息
     * @返回 bool
     */
    public static function set_user_login_status(string $token,$user_info) : bool
    {

        $cacheKey       = CacheKeyController::$USER_LOGIN_STATUS;
        $userCacheKey   = $cacheKey['key'] . $token;

        if (!is_array($user_info)){
            $user_info = $user_info->toArray();
        }

        if ($user_info)
        {
            Cache::store('redis')->put($userCacheKey,$user_info,$cacheKey['time']);
            Cache::store('redis')->put($user_info['id'],$userCacheKey,$cacheKey['time']);

        }
        return true;
    }



    public static function sendCode($phone=17602114904,$token='',$tempId=0,$sign='归仁商城',$smsDemo = SmsDemo::class)
    {
        // 0信息变更验证码 1修改密码验证码 2用户注册验证码  3登录异常验证码  4登录确认验证码  5短信测试   6身份验证验证码  7.SMS_112465127 提现
        $tempArr = ["SMS_142055523"];

        $demo = new $smsDemo();

        $code = (string)rand(1000, 9999);
        $end_time   = time() + 15*60;
        Redis::HMSET('user_sms_'.$phone, ['code'=>$code , 'end_time'=> $end_time]);
        Redis::EXPIRE ('user_sms_'.$phone,15*60);
        session(['user_sms_'.$phone => ['code'=>$code , 'end_time'=>time() + 15*60 ]]);
        $response = $demo->sendSms(
            $sign, // 短信签名
            $tempArr[$tempId], // 短信模板编号
            $phone, // 短信接收者
            Array(  // 短信模板中字段的值
                "code"      => $code
            ),
            "123"
        );
        $res = ['code'=>$code,'phone'=>$phone,'msg'=>'操作成功'];
        return $res;
    }
    public static function check_sms_code(string $phone,int $code) : bool
    {
//        $user_session = session("user_sms_".$phone);
        $user_session = Redis::HGETALL("user_sms_".$phone);
        if ($user_session['end_time'] < time())
        {
            return false;
        }
        if ($user_session['code'] != $code)
        {
            return false;
        }
        //校验成功后要删除验证码缓存
//        session(["user_sms_".$phone => []]);
        return true;
    }

}
